package group.cyfc.studygo.service;

import group.cyfc.studygo.dao.UserRepository;
import group.cyfc.studygo.dto.JsonResult;
import group.cyfc.studygo.entity.User;
import group.cyfc.studygo.util.SnowflakeIdWorker;
import group.cyfc.studygo.vo.UserVo;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import org.codehaus.xfire.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.*;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    /**
     * 排名显示人数
     */
    private final static int RANKING_NUM = 5;

    /**
     * APP_ID
     */
    private final static String APP_ID = "wx670636e9cc300234";

    /**
     * APP_SECRET
     */
    private final static String APP_SECRET = "0dfab8485438c11d3cd8cfa088668859";


    public JsonResult managerLogin(String username, String password){
        User user = userRepository.userLogin(username,password);
        if(user==null){
            return new JsonResult<>().clientError(HttpStatus.UNPROCESSABLE_ENTITY,"管理员不存在或密码错误",username);
        }else {
            UserVo userVo = toUserVo(user);
            return new JsonResult<>().ok("ok",userVo);
        }
    }

    public JsonResult saveUser(UserVo userVo){
        try {
            User user = new User();
            BeanUtils.copyProperties(userVo,user);
            user.setId(snowflakeIdWorker.nextId());
            user.setCreateBy(1L);
            user.setCreateAt(new Date());
            user.setUpdateBy(1L);
            user.setUpdateAt(new Date());
            user.setScore(0);
            userRepository.save(user);
            return new JsonResult().ok("saveUser success");
        }catch (Exception e){
            return new JsonResult().serverError("error");
        }
    }

    public JsonResult getUserByUsername(String username){
        User user = userRepository.findUserByUsernameAndIsDel(username,false);
        if(user==null){
            return new JsonResult<>().clientError(HttpStatus.UNPROCESSABLE_ENTITY,"用户不存在",username);
        }else {
            UserVo userVo = toUserVo(user);
            return new JsonResult<>().ok("ok",userVo);
        }
    }

    public JsonResult addScore(UserVo userVo){
        JsonResult result = getUserByUsername(userVo.getUsername());
        if(result.getCode().equals(HttpStatus.UNPROCESSABLE_ENTITY)){
            return result;
        }else {
            UserVo user = (UserVo) result.getData();
            userRepository.addScore(user.getUsername(),userVo.getScore());
            return new JsonResult().ok("ok");
        }
    }

    public JsonResult getRanking(String username){
        JsonResult jsonResult = getUserByUsername(username);
        if(jsonResult.getCode().equals(HttpStatus.UNPROCESSABLE_ENTITY)){
            return jsonResult;
        }

        Sort sort = new Sort(Sort.Direction.DESC,"score");
        List<User> list = userRepository.findAll(sort);

        //排行榜信息
        List<UserVo> resultList = new ArrayList<>();
        int index = 1;
        for(int i=0;i<RANKING_NUM;i++){
            UserVo userVo = new UserVo();
            if(i==0){
                userVo = toUserVo(list.get(i));
                userVo.setId(list.get(i).getId().toString());
                userVo.setRank(1);
                resultList.add(userVo);
            }else if(list.get(i).getScore().equals(list.get(i-1).getScore())){
                userVo = toUserVo(list.get(i));
                userVo.setId(list.get(i).getId().toString());
                userVo.setRank(index);
                resultList.add(userVo);
            }else {
                index = i+1;
                userVo = toUserVo(list.get(i));
                userVo.setId(list.get(i).getId().toString());
                userVo.setRank(index);
                resultList.add(userVo);
            }
        }
        //个人排名

        UserVo thisUser = (UserVo) jsonResult.getData();
        boolean flag = false;
        for(int i=0;i<resultList.size();i++){
            if(resultList.get(i).getId().equals(thisUser.getId())){
                thisUser.setRank(resultList.get(i).getRank());
                flag = true;
                break;
            }
        }
        User thisUserEn = new User();
        BeanUtils.copyProperties(thisUser,thisUserEn);
        thisUserEn.setId(Long.valueOf(thisUser.getId()));
        if(!flag){
            thisUser.setRank(list.indexOf(thisUserEn)+1);
        }
        List<UserVo> myRank = new ArrayList<>();
        myRank.add(thisUser);

        List<List<UserVo>> rankList = new ArrayList<>();
        rankList.add(resultList);
        rankList.add(myRank);
        return new JsonResult<>().ok("ok",rankList);
    }

    public JsonResult userLogin(JSONObject data){
        String code = (String) data.get("code");
        String encryptedData = (String)data.get("encryptedData");
        String iv = (String)data.get("iv");
        String sessionKeyAndopenId = getSessionKey(code);
        JSONObject jsonObject = JSONObject.parseObject(sessionKeyAndopenId);
        String sessionKey = (String) jsonObject.get("session_key");
        JSONObject userInfo = getUserInfo(encryptedData,sessionKey,iv);
        String unionId = (String)userInfo.get("unionId");
        JsonResult jsonResult = getUserByUsername(unionId);
        if(jsonResult.getCode().equals(HttpStatus.UNPROCESSABLE_ENTITY)){
            return new JsonResult<>().ok("saveUser",userInfo);
        }else {
            UserVo userVo = (UserVo) jsonResult.getData();
            return new JsonResult<>().ok("ok",userVo);
        }
    }

    /**
     * 访问微信接口获取解密密钥
     * @param code
     * @return
     */
    public String getSessionKey(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret="
                + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        String strbody=restTemplate.exchange(url, HttpMethod.GET, entity,String.class).getBody();
        return strbody;
    }

    public JSONObject getUserInfo(String encryptedData,String sessionkey,String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64. decode(sessionkey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "utf-8");
                return JSONObject.parseObject(result);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将User实体对象转化成Vo对象
     * @param user
     * @return
     */
    private UserVo toUserVo(User user){
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        userVo.setId(user.getId().toString());
        return userVo;
    }
}